<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- <el-col :span="20" :xs="24"> -->

      <!-- </el-col> -->
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <!-- <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['31510']"
              @click="handleAdd"
              >指定培训课程</el-button
            >
          </el-col>
          <el-form
            :model="queryParams"
            ref="queryForm"
            v-show="showSearch"
            :inline="true"
            label-width="80px"
            @submit.native.prevent
          >
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="请输入标题名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
                size="small"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="分类名称" prop="titleName" align="center" />
          <el-table-column label="课程数量" prop="titleName" align="center" />
          <el-table-column label="分类简介" prop="titleName" align="center" />
          <!-- <el-table-column label="顺序号" prop="titleName" align="center" /> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!-- <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['31520']"
                  @click="handleUpdate(scope.row)"
                >修改</el-button> -->
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['31530']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />
        <!-- 添加或修改角色配置对话框 -->
        <!-- :class="{'add-person': !form.id}" -->
        <el-dialog
          width="980px"
          :visible.sync="open"
          :title="title"
          append-to-body
        >
          <el-row :gutter="24">
            <el-col :span="4">
              <div>
                <el-tree
                  :data="quesCateOptions"
                  show-checkbox
                  node-key="id"
                  :default-expanded-keys="[2, 3]"
                  :default-checked-keys="[5]"
                  :props="defaultProps"
                >
                </el-tree>
              </div>
            </el-col>
            <el-col :span="20" class="multiple">
              <el-table v-loading="loading" :data="questionList" :border="true">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column
                  label="课程名称"
                  prop="nickName"
                  align="center"
                  :show-overflow-tooltip="true"
                  width="160"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="nickName"
                  label="课程介绍"
                  width="160"
                />
                <el-table-column
                  align="center"
                  prop="nickName"
                  label="培训课时"
                  width="160"
                />
                <el-table-column
                  label="课程类型"
                  prop="dept.deptName"
                  align="center"
                  width="150"
                ></el-table-column>
                <el-table-column
                  label="状态（启用/禁用）"
                  align="center"
                  key="enable"
                >
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.enable"
                      :active-value="1"
                      :inactive-value="0"
                      @change="handleStatusChange(scope.row)"
                    ></el-switch>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getPage,
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/system/dict";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import dict from "@/assets/json/dict.json";

export default {
  name: "trainMatrix",
  components: { Treeselect },
  data() {
    return {
      // activeName: 'first',
      treeName: undefined,
      treeOptions: [],
      currentId: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        dictId: this.currentId,
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        titleName: [
          { required: true, message: "标题名称不能为空", trigger: "blur" },
        ],
        dictId: [
          { required: true, message: "请选择上级类别", trigger: "change" },
        ],
      },
      statusOptions: [],
    };
  },
  computed: {},
  watch: {
    // 根据名称筛选树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.statusOptions = dict.roles;
    /**created
     * 1. 页面内容（仅在进入页面时，调用此接口）
     *    树 1. 赋值树数据（之后不会被改变） 2. dictId tid 赋初始值（currentId）
     *    调用“获取表格数据”方法
     * 2. 获取下拉框
     *
     * methods
     * 1. 点击树节点
     *    1. 获取树节点id 作为 dictId tid（currentId）
     *    2. 调用“获取表格数据”接口
     * 2. 获取表格数据（树节点+关键字）
     *    this.queryParams.dictId = this.currentId; //防止首次进入页面，queryParams.dictId无值，但是修改成功后无法定位当前修改行
     * 3. 添加，修改，删除
     *    方法一：判断 dictId tid 是否存在，如果不存在 -> 提示“请先点击树结构”
     *    方法二：获取页面内容时，将 dictId tid 赋初始值
     *
     * 注：一级数据，添加/修改/删除都不能操作
     * 注： tid为0的这一级 都没有添加的功能
     *     （它的同级不能添加，但是它的子级可以添加，
     *       所以，当选中它，表格中展示的是它的下级，所以可以添加，
     *       且此时的顶级id应该是，它的子级的顶级id，也就是它的id）
     */

    this.getPageInfo();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
        this.currentId = response.result.data[0].id; //将节点id赋值给上级id
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        // this.defaultExpandkeys[0] = this.currentId;
        this.getList();
      });
    },
    getList() {
      this.loading = true;
      this.queryParams.dictId = this.currentId;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.currentId = data.id; //id
      // this.defaultExpandkeys[0] = this.currentId;   //下一次获取树，默认展开的节点
      this.getList();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.id;
      getData(theId).then((response) => {
        this.form = response.result;
        // this.form.dictId = this.currentId
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        tid: this.currentId,
        dictId: this.currentId,
        titleName: undefined,
        sort: 0,
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const theId = row.id;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ .el-form {
  display: inline-block;
  position: relative;
  top: -5px;
}
/deep/ .el-form-item {
  margin-bottom: 0;
}
/deep/ .el-tabs__item {
  font-size: 16px;
}
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
.add-person /deep/ .el-dialog__body {
  min-height: 240px;
}
</style>